package com.leyou.sms.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.leyou.sms.config.SmsProperties;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.system.SystemProperties;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Data
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtil {
    Logger log = LoggerFactory.getLogger(SmsUtil.class);
    @Autowired
    SmsProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "sms:phone:";
    private static final long SMS_MIN_INTERVAL_IN_MILLIS = 60000;
    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyun.com";
    public SendSmsResponse sendSms(String phoneNumber, String signName, String templateCode, String templateParam) {
        try {
            String key = KEY_PREFIX + phoneNumber;
            String lastTime = redisTemplate.oprForValue().get(key);
            if(StringUtils.isBlank(lastTime)){
                Long last = Long.valueOf(lastTime);
                if(System.currentTimeMillis() - last < SMS_MIN_INTERVAL_IN_MILLIS){
                    log.info("[短信服务] 发送短信频率过高，被拦截，手机号：{}", phoneNumber);
                    return null;
                }
            }

           //可自动调整超时时间
           System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
           System.setProperty("sun.net.client.defaultReadTimeout", "10000");
           //初始化acsClient，暂不支持region化
           IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", prop.getAccessKeyId(), prop.getAccessKeySecret());
           DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
           DefaultAcsClient defaultAcsClient = new DefaultAcsClient(profile);
           //组装请求对象
           SendSmsRequest request = new SendSmsRequest();
           request.setMethod(MethodType.POST);
           request.setPhoneNumbers(phoneNumber);
           //短信签名
           request.setSignName(signName);
           //短信模板
           request.setTemplateCode(templateCode);
           //模板参数
           request.setTemplateParam(templateParam);

           SendSmsResponse acsResponse = defaultAcsClient.getAcsResponse(request);
           if (!"OK".equals(acsResponse.getCode())) {
               log.error("【短信服务】发送短信失败，phonenumber:{}，原因：{}", phoneNumber, acsResponse.getMessage());
           }

            redisTemplate.oprForValue().set(key,String.valueOf(System.currentTimeMillis()),1, TimeUnit.MINUTES);
           return acsResponse;


       }catch (Exception e){
       }
       return  null;
    }
}
